package com.xsh.gls.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xsh.gls.mapper.SalesmanMapper;
import com.xsh.gls.pojo.*;
import com.xsh.gls.service.SalManService;
import com.xsh.gls.service.Type_FunctionalService;
import com.xsh.gls.service.UserService;
import com.xsh.gls.service.UserTypeService;
import com.xsh.gls.utils.RedisUtils;
import com.xsh.gls.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("userInfo")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserTypeService userTypeService;
    @Autowired
    private SalManService salManService;
    @Autowired
    private Type_FunctionalService type_functionalService;
    @Autowired
    private RedisUtils redisUtils;
    @RequestMapping("/toUserInfo")
    public PageInfo<User> toUserInfo(@RequestParam(required = false) String userName, @RequestParam(required = false) String pageNum,
                                     @RequestParam(required = false) String sAddress, @RequestParam(required = false) Integer typeId) {
        Integer _pageNum = 1;
        List<User> list = null;
        if (pageNum != null && !pageNum.equals("")) {
            _pageNum = Integer.parseInt(pageNum);
        }
        PageHelper.startPage(_pageNum, 5, "TYPEID");
        try {
            list = userService.queryAll(userName, sAddress, typeId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PageInfo<User> page = new PageInfo<User>(list);
        return page;
    }

    @RequestMapping("/userType")
    public List<User_Type> userType() {
        List<User_Type> listType = null;
        try {
            listType = userTypeService.queryAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listType;
    }

    @RequestMapping("/Reset")
    public Transfer Reset(Integer id) {
        Transfer transfer = new Transfer();
        String password = SecurityUtils.md5Hex("111111");
        if (userService.updatePwdById(password, id)) {
            transfer.setMessage("yes");
        } else {
            transfer.setMessage("no");
        }
        return transfer;
    }

    @RequestMapping("/addUser")
    public Transfer addUser(String userName, String sName, Integer typeId, String sAddress, String pwd, String phone, String email, String idCard) {
        Transfer transfer = new Transfer();
        String password = SecurityUtils.md5Hex(pwd);
        User user = new User();
        user.setUsername(userName);
        user.setPhone(phone);
        user.setPassword(password);
        user.setTypeid(typeId);
        Salesman salesman = new Salesman();
        salesman.setsName(sName);
        salesman.setsAddress(sAddress);
        salesman.setsEmail(email);
        salesman.setsIdcard(idCard);
        try {
            if (userService.insert(user, salesman)) {
                transfer.setMessage("yes");
            } else {
                transfer.setMessage("no");
            }
        } catch (Exception e) {
            e.printStackTrace();
            transfer.setMessage("no");
        }
        return transfer;
    }

    @RequestMapping("/toUpdate")
    public User toUpdate(Integer id) {
        User user = null;
        try {
            user = userService.selectUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    @RequestMapping("/hasUserName")
    public Transfer hasUserName(String userName, String oldusername) {
        Transfer transfer = new Transfer();
        User user = null;
        try {
            user = userService.selectByUserNameOld(userName, oldusername);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user == null) {
            transfer.setMessage("yes");
        } else {
            transfer.setMessage("no");
        }
        return transfer;
    }

    @RequestMapping("/hasPhone")
    public Transfer hasPhone(String phone, String oldPhone) {
        Transfer transfer = new Transfer();
        User user = null;
        try {
            user = userService.selectByPhoneOld(phone, oldPhone);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user == null) {
            transfer.setMessage("yes");
        } else {
            transfer.setMessage("no");
        }
        return transfer;
    }

    @RequestMapping("/hasIdCard")
    public Transfer hasIdCard(String IdCard, @RequestParam(required = false) String oldIdCard) {
        Transfer transfer = new Transfer();
        Salesman salesman = null;
        try {
            salesman = salManService.selectByIdCard(IdCard, oldIdCard);
        } catch (Exception e) {
            e.printStackTrace();
            transfer.setMessage("no");
        }
        if (salesman == null) {
            transfer.setMessage("yes");
        } else {
            transfer.setMessage("no");
        }
        return transfer;
    }

    @RequestMapping("/updateUser")
    public Transfer updateUser(Integer id, Integer salId, String userName, String sName, Integer typeId, String phone, String email, String idCard) {
        Transfer transfer = new Transfer();
        User user = new User();
        Salesman salesman = new Salesman();
        user.setId(id);
        user.setUsername(userName);
        user.setPhone(phone);
        if(salId!=null) {
            user.setSalid(salId);
            salesman.setId(salId);
        }


        salesman.setsName(sName);
        salesman.setsEmail(email);
        salesman.setsIdcard(idCard);
        try {
            if (userService.updateById(user, salesman)) {
                transfer.setMessage("yes");
            } else {
                transfer.setMessage("no");
            }
        } catch (Exception e) {
            e.printStackTrace();
            transfer.setMessage("no");
        }
        return transfer;
    }

    @RequestMapping("/delUser")
    public Transfer delUser(Integer id) {
        Transfer transfer = new Transfer();
        try {
            if (userService.delUser(id)) {
                transfer.setMessage("yes");
            } else {
                transfer.setMessage("no");
            }
        } catch (Exception e) {
            e.printStackTrace();
            transfer.setMessage("no");
        }
        return transfer;
    }

    @RequestMapping("/updatepwd")
    public Transfer updatepwd(String password,String pwd,HttpServletRequest request) {
        Transfer transfer = new Transfer();
        try {
            User user=(User)request.getAttribute("user");
            String oldPwd=user.getPassword();
            if (oldPwd.equals(SecurityUtils.md5Hex(pwd))) {
                User u=new User();
                u.setId(user.getId());
                u.setPassword(SecurityUtils.md5Hex(password));
                if(userService.updateByPrimaryKeySelective(u)==1){
                    transfer.setMessage("yes");
                }else{
                    transfer.setMessage("no");
                }
            } else {
                transfer.setMessage("nopwd");
            }
        } catch (Exception e) {
            e.printStackTrace();
            transfer.setMessage("no");
        }
        return transfer;
    }

    @RequestMapping("/toUser")
    public User toUser(HttpServletRequest request) {
        User user = (User) request.getAttribute("user");
        return user;
    }

    @RequestMapping(value = "/saveUserinfo")
    public Transfer saveUserinfo(@RequestParam(value = "userImg", required = false) MultipartFile attachs,
                                 @RequestParam(value = "realname", required = false) String realname,
                                 @RequestParam(value = "phone", required = false) String phone,
                                 @RequestParam(value = "address", required = false) String address,
                                 @RequestParam(value = "idcard", required = false) String idcard,
                                 @RequestParam(value = "email", required = false) String email, HttpServletRequest request) {
        String logoPicPath = null;// LOGO图片url路径
        String logoLocPath = null;// LOGO图片的服务器存储路径
        Transfer transfer = new Transfer();

        //判断上传文件是否为空
        if (attachs!=null) {
            //原有图片名字
            String oldFileName = attachs.getOriginalFilename();
            //后缀
            String prefix = oldFileName.substring(oldFileName.lastIndexOf(".") + 1);
            //存储路径
            String path = "D:\\nginx-1.14.2\\html\\images";
            if (attachs.getSize() > 500000) {
                transfer.setMessage("size");
                return transfer;
            } else if (prefix.equalsIgnoreCase("jpg")
                    || prefix.equalsIgnoreCase("jpeg")
                    || prefix.equalsIgnoreCase("png")
                    || prefix.equalsIgnoreCase("pneg")) {
                //新名字
                String newFileName = UUID.randomUUID().toString()
                        .replace("-", "")
                        + "." + prefix;
                File file = new File(path, newFileName);
                try {
                    attachs.transferTo(file);
                } catch (Exception e) {
                    e.printStackTrace();
                    transfer.setMessage("fail");
                    return transfer;
                }
                logoPicPath = "images" + File.separator + newFileName;
                logoLocPath = path + File.separator + newFileName;

            }


        }
            User user = (User) request.getAttribute("user");
            int typeId = user.getTypeid();
            int salid = user.getSalid();
            int cusid = user.getCusid();
            if (phone != null && !phone.equals("")) {
                user.setPhone(phone);
            }
            if (typeId < 10) {
                Salesman salesman = new Salesman();
                if (logoLocPath != null && !logoPicPath.equals("")) {
                    salesman.setsImagelocpath(logoLocPath);
                }
                if (logoPicPath != null && !logoPicPath.equals("")) {
                    salesman.setsImagepicpath(logoPicPath);
                }

                if (email != null && !email.equals("")) {
                    salesman.setsEmail(email);
                }
                if (address != null && !address.equals("")) {
                    salesman.setsAddress(address);
                }
                if (realname != null && !realname.equals("")) {
                    salesman.setsName(realname);
                }
                if (idcard != null && !idcard.equals("")) {
                    salesman.setsIdcard(idcard);
                }
                try {
                    if (userService.updatePhone1(user, salesman, salid)) {
                        transfer.setMessage("yes");
                    } else {
                        transfer.setMessage("fail");
                        return transfer;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    transfer.setMessage("fail");
                    return transfer;
                }

            } else {
                Customer customer = new Customer();

                if (logoLocPath != null && !logoLocPath.equals("")) {
                    customer.setcImagelocpath(logoLocPath);
                }
                if (logoPicPath != null && !logoPicPath.equals("")) {
                    customer.setcImagepicpath(logoPicPath);
                }
                if (email != null && !email.equals("")) {
                    customer.setcEmail(email);
                }
                if (address != null && !address.equals("")) {
                    customer.setcAddress(address);
                }
                if (realname != null && !realname.equals("")) {
                    customer.setcUsername(realname);
                }
                if (idcard != null && !idcard.equals("")) {
                    customer.setIdcard(idcard);
                }
                try {
                    if (userService.updatePhone2(user, customer, cusid)) {
                        transfer.setMessage("yes");
                    } else {
                        transfer.setMessage("fail");
                        return transfer;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    transfer.setMessage("fail");
                    return transfer;
                }
            }
        User user1=null;
        List<Type_Functional> funList=null;
        String token=UUID.randomUUID().toString().replace("-","");
        System.out.println(token);
        try {
            user1=userService.queryUserByUserName(user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(user==null){
            transfer.setMessage("no");
            return transfer;
        }else {
                try {
                    funList= type_functionalService.queryFunctionByTypeId(user1.getTypeid());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                user1.setFunList(funList);
                redisUtils.del(request.getParameter("token"));
                redisUtils.set(token,user1);
                transfer.setMessage("yes");
                transfer.getMap().put("token",token);
            return transfer;
            }

        }

}
